package com.point.ootb.util;

import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.point.ootb.core.ServiceException;
import com.point.ootb.domain.vo.LoginUserInfoVO;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
@NoArgsConstructor
@Data
public class LoginInfoUtil {

    public static final String LOGIN_USER_KEY = "loginUser";
    private static final ThreadLocal<LoginUserInfoVO> LOGIN_CACHE = new ThreadLocal<>();

    public static void login(LoginUserInfoVO loginUser) {
        LOGIN_CACHE.set(loginUser);
        StpUtil.login(loginUser.getUserId());
        setLoginUser(loginUser);
    }

    public static void setLoginUser(LoginUserInfoVO loginUser) {
        StpUtil.getTokenSession().set(LOGIN_USER_KEY, loginUser);
    }

    public static LoginUserInfoVO getLoginUser() {
        LoginUserInfoVO loginUser = LOGIN_CACHE.get();
        //String--->loginUser
        if (loginUser == null) {
            try {
                loginUser = (LoginUserInfoVO) StpUtil.getTokenSession().get(LOGIN_USER_KEY);
            } catch (SaTokenException var2) {
                throw new ServiceException("登录信息已过期");
            }

        }
        return loginUser;
    }

    public static Long getUserId() {
        LoginUserInfoVO loginUser = getLoginUser();
        if (ObjectUtil.isNull(loginUser)) {
            return Long.valueOf(StpUtil.getLoginIdAsString());
        } else {
            return loginUser.getUserId();
        }
    }
}
